var express = require("express");
const db = require("../db.js");
var router = express.Router();

/* GET home page. */
router.get("/", function (req, res, next) {
  var sql =
    "SELECT id,name,price,image,add_time FROM product order by add_time desc limit 0,4";
  db.conn.query(sql, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ]", err.message);
      return;
    }
    console.log(result);
    res.render("index.ejs", { products: result });
  });
});
router.get("/product", function (req, res, next) {
  var cat_id = req.query.cat_id;
  if (cat_id) {
    var sqlStr = "select * from product where cat_id=? order by id desc";
    var sqlParam = [cat_id];
  } else {
    var sqlStr = "select * from product order by id desc";
    var sqlParam = [];
  }
  db.conn.query(sqlStr, sqlParam, function (err, result) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(result);
    res.render("productList.ejs", { products: result });
  });
});
router.get('/detail/:id', function (req, res,next) {
  var id = req.params.id;
  var sqlStr = "select id,image,name,price,content from product where id = ?";
  var sqlParam = [id];
  db.conn.query(sqlStr, sqlParam, function (err, result) { 
    if (err) {
      console.log(err);
      return;
    }
    console.log(result);
    res.render('detail.ejs',{oneProduct:result})    
  });
})
router.get('/page/:pid', function (req, res, next) { 
  var pid = req.params.pid;
  var sqlstr = "select id,page_name,content from page where id = ?";
  var sqlParam = [pid];
  db.conn.query(sqlstr, sqlParam, function (err, result) { 
    if (err) {
      console.log(err);
      return;
    }
    console.log(result);
    res.render('page.ejs',{pageContent:result})
  })
})

module.exports = router;
